'''
Created on 06/12/2009

@author: Oded
'''
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
import re
import urllib


class User_formulas(db.Model):
    user = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    formula = db.BooleanProperty(default=True)
    
class UserConstants(db.Model):
    user = db.UserProperty()
    name = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)   
    
class Notebooks(db.Model):
    nbID = db.StringProperty()
    formulaID = db.ReferenceProperty(User_formulas)
    date = db.DateTimeProperty(auto_now_add=True)

class NotebooksConst(db.Model):
    nbID = db.StringProperty()
    formulaID = db.ReferenceProperty(UserConstants)
    date = db.DateTimeProperty(auto_now_add=True)
    
def GetPlot(formula):
    wolfUrl = "http://www.wolframalpha.com/input/" 
    data = fetch(wolfUrl + "?" + urllib.urlencode({'i': formula})).content
    reg = "asynchronousPod\\('(.*?)', ?'0200',.*\\)"
    try:
        m = re.search(reg,data)
        html = fetch(wolfUrl + m.group(1)).content
        m = re.search('<div class="output".*</div>', html)
        return m.group(0)
    except:
        return "TimeOut"
    
